package com.vken.blog.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.vken.blog.model.User;
import com.vken.blog.service.UserManager;

public class UserAction extends ActionSupport {
	private static final long serialVersionUID = 5601509010351814691L;
	private User user;
	private UserManager userManager;
	private String message;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public String getMessage() {
		return message;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}

	public String login() {
		User user2 = userManager.get(user.getUsername(), user.getPassword());
		if (user2 != null) {
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.setAttribute("user", user2);
			return SUCCESS;
		} else {
			message = "用户名或者密码输入错误";
			return INPUT;
		}
	}

	public String logout() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.invalidate();
		return SUCCESS;
	}

	public String changePassword() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String oldPwd = request.getParameter("oldPassword");
		String newPwd = request.getParameter("newPassword");
		String reNewPwd = request.getParameter("reNewPassword");

		if (!newPwd.equals(reNewPwd)) {
			message = "输入的两次新密码不相符";
			return INPUT;
		}

		HttpSession session = ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute("user");
		if (!user.getPassword().equals(oldPwd)) {
			message = "旧密码输入不正确";
			return INPUT;
		}
		user.setPassword(newPwd);
		userManager.changePassword(user.getId(), newPwd);
		message = "修改密码成功";
		return SUCCESS;
	}
}
